package cn.wei.sdd.core.service.impl;

import cn.wei.common.exception.Assert;
import cn.wei.common.result.ResponseEnum;
import cn.wei.sdd.core.enums.CheckStatusEnum;
import cn.wei.sdd.core.enums.HandleStatusEnum;
import cn.wei.sdd.core.enums.TransStatusEnum;
import cn.wei.sdd.core.mapper.*;
import cn.wei.sdd.core.pojo.entity.*;
import cn.wei.sdd.core.pojo.vo.CheckOrdersVO;
import cn.wei.sdd.core.pojo.vo.OrderItemVO;
import cn.wei.sdd.core.service.OrderService;
import cn.wei.sdd.core.service.PackOrdersService;

import cn.wei.sdd.core.service.UserService;
import cn.wei.sdd.core.utils.CheckCodeUtil;
import cn.wei.sdd.core.utils.MyEncryptUtils;
import cn.wei.sdd.core.utils.NoUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 订单打包记录表 服务实现类
 * </p>
 *
 * @author Wei
 * @since 2021-10-31
 */
@Service
public class PackOrdersServiceImpl extends ServiceImpl<PackOrdersMapper, PackOrders> implements PackOrdersService {

    @Resource
    private OrdersMapper ordersMapper;

    @Resource
    private OrderItemMapper orderItemMapper;


    @Resource
    private TransFlowMapper transFlowMapper;

    @Resource
    private OrderService orderService;

    @Resource
    private UserService userService;

    @Resource
    private UserMapper userMapper;

    @Resource
    CheckRecordMapper checkRecordMapper;


    @Resource
    private UserAccountMapper userAccountMapper;

    @Resource
    private InWarehouseMapper inWarehouseMapper;


    @Resource
    private WarehouseProductMapper warehouseProductMapper;

    @Resource DictMapper dictMapper;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void pack(List<String> ids, Long userId) {
        Assert.notNull(ids, ResponseEnum.PAY_UNIFIEDORDER_ERROR);
        String str = "";
        for (int i = 0; i < ids.size(); i++){
            if(i== ids.size()-1){
                str+= ids.get(i);
                Orders orders = new Orders();
                orders.setId(Long.parseLong(ids.get(i)));
                orders.setRecyclerStatus(HandleStatusEnum.PACK_CHECK.getStatus());
                ordersMapper.updateById(orders);
            }else{
                str+= ids.get(i)+",";
                Orders orders = new Orders();
                orders.setId(Long.parseLong(ids.get(i)));
                orders.setRecyclerStatus(HandleStatusEnum.PACK_CHECK.getStatus());
                ordersMapper.updateById(orders);
            }

        }
        PackOrders packOrders = new PackOrders();
        packOrders.setPackNo(NoUtils.getPackNo());
        //加密验收码
        try {
            packOrders.setCheckCode(MyEncryptUtils.AESencrypt(CheckCodeUtil.randomCheckCode()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        packOrders.setOrdersIds(str);
        packOrders.setRecyclerId(userId);
        packOrders.setStatus(CheckStatusEnum.NOT_CHECK.getStatus());
        baseMapper.insert(packOrders);

    }

    @Override
    public List<CheckOrdersVO> getCheckOrders(Long userId) {
//        1、根据回收员id和打包状态查询打包列表
        QueryWrapper<PackOrders> packOrdersQueryWrapper = new QueryWrapper<>();
        packOrdersQueryWrapper
                .eq("recycler_id",userId)
                .eq("status", CheckStatusEnum.NOT_CHECK.getStatus());
        List<PackOrders> packOrdersList = baseMapper.selectList(packOrdersQueryWrapper);

        return this.getListByPackOrdersList(packOrdersList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void check(String packNo, String checkCode, Long userId) {

        /**
         * 分析：
         *  1、验收成功
         *  2、物品存入仓库
         *  3、回收员更改账户余额，添加流水
         *  4、添加验收记录
         *  5、更改打包订单状态
         */
        QueryWrapper<PackOrders> packOrdersQueryWrapper = new QueryWrapper<>();
        packOrdersQueryWrapper.eq("pack_no",packNo)
        .eq("status",CheckStatusEnum.NOT_CHECK.getStatus());
        PackOrders packOrders = baseMapper.selectOne(packOrdersQueryWrapper);

        Assert.notNull(packOrders,ResponseEnum.IS_CHECK_CODE_ERROR);
        //回收员id
        Long recyclerId = packOrders.getRecyclerId();


        //判断验收码是否一致
        String trueCode ="";
        try {
           trueCode = MyEncryptUtils.AESdecrypt(packOrders.getCheckCode());
        } catch (Exception e) {
            e.printStackTrace();
        }
        Assert.equals(trueCode,checkCode,ResponseEnum.CHECK_CODE_ERROR);


        //更改打包验收状态
        PackOrders UpdatePackOrders = new PackOrders();
        UpdatePackOrders.setId(packOrders.getId());
        UpdatePackOrders.setCheckerId(userId);
        UpdatePackOrders.setStatus(CheckStatusEnum.IS_Check.getStatus());
        baseMapper.updateById(UpdatePackOrders);



        //获取打包的所有订单id
      String ids = packOrders.getOrdersIds();
      String[] splitId = ids.split(",");

      //打包订单总金额
      BigDecimal totalPrice = new BigDecimal(0.0);
      for (String id : splitId) {
            //更新订单状态
            Orders orders = new Orders();
            orders.setId(Long.valueOf(id));
            orders.setRecyclerStatus(HandleStatusEnum.FINISH_ORDER.getStatus());
            ordersMapper.updateById(orders);

            //计算订单总价
            BigDecimal price = orderService.getTotalPriceByOrdersId(Long.valueOf(id));
            //累加
            totalPrice= totalPrice.add(price) ;

            //入库
          QueryWrapper<OrderItem> orderItemQueryWrapper = new QueryWrapper<>();
          orderItemQueryWrapper.eq("order_id",Long.valueOf(id));
          List<OrderItem> orderItems = orderItemMapper.selectList(orderItemQueryWrapper);
          String inNo = NoUtils.getInNo();
          for (OrderItem item : orderItems) {
             //添加入库记录
              String parentName = dictMapper.getParentNameByDictId(item.getDictId());
              InWarehouse inWarehouse = new InWarehouse();
              inWarehouse.setInNo(inNo);
              inWarehouse.setDictId(item.getDictId());
              inWarehouse.setInNum(item.getWeight());
              inWarehouse.setOperatorId(userId);
              inWarehouse.setParentName(parentName);
              inWarehouse.setPackNo(packNo);
              inWarehouseMapper.insert(inWarehouse);

              //入库
              WarehouseProduct warehouseProduct = new WarehouseProduct();
              //查询当前商品库存
              QueryWrapper<WarehouseProduct> warehouseProductQueryWrapper = new QueryWrapper<>();
              warehouseProductQueryWrapper.eq("dict_id",item.getDictId());
              WarehouseProduct product = warehouseProductMapper.selectOne(warehouseProductQueryWrapper);
              //当前商品数量
              Double currentNum = item.getWeight();
              if (product!=null){
                  //加上原来数量
                  currentNum+=product.getCurrentNum();
              }
              warehouseProduct.setDictId(item.getDictId());
              warehouseProduct.setCurrentNum(currentNum);

              //如果没有当前商品，插入数据
              if (product==null){
                  warehouseProduct.setParentName(parentName);
                  warehouseProductMapper.insert(warehouseProduct);
              }else{
                  //存在更新
                  warehouseProduct.setId(product.getId());
                  warehouseProductMapper.updateById(warehouseProduct);
              }


          }


      }

        //获取用户信息
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("user_type",User.Recycler)
                .eq("id",recyclerId);
        User user = userMapper.selectOne(userQueryWrapper);

        //获取用户提成百分比
        BigDecimal percent = userService.getPercentByUserId(recyclerId);
        //相乘,取百分比
        percent = percent.multiply(BigDecimal.valueOf(0.01));
        //计算提成
        BigDecimal tiCheng = totalPrice.multiply(percent).setScale(2, BigDecimal.ROUND_HALF_UP);


        //更新用户账户
        QueryWrapper<UserAccount> userAccountQueryWrapper = new QueryWrapper<>();
        userAccountQueryWrapper.eq("user_type",User.Recycler)
                .eq("user_id",recyclerId);

        UserAccount userAccount = new UserAccount();
        //获取原有金额
        UserAccount account = userAccountMapper.selectOne(userAccountQueryWrapper);

        userAccount.setId(account.getId());
        BigDecimal amount = account.getAmount().setScale(2, BigDecimal.ROUND_HALF_UP);

        amount = amount.add(tiCheng);
        userAccount.setAmount(amount);
        userAccountMapper.updateById(userAccount);



        //添加流水
        TransFlow transFlow = new TransFlow();
        transFlow.setUserType(User.Recycler);
        transFlow.setUserId(recyclerId);
        transFlow.setTransNo(NoUtils.getTransNo());
        transFlow.setUserName(user.getUserName());
        transFlow.setTransType(TransStatusEnum.INCOME.getStatus());
        transFlow.setTransTypeName(TransStatusEnum.INCOME.getMsg());
        transFlow.setTransAmount(tiCheng);
        transFlow.setMemo("打包订单收入，打包号："+packOrders.getPackNo());
        transFlowMapper.insert(transFlow);

        //添加验收记录
//        CheckRecord checkRecord = new CheckRecord();
//        checkRecord.setCheckerId(userId);
//        checkRecord.setPackNo(packNo);
//        checkRecordMapper.insert(checkRecord);


    }

    public  List<CheckOrdersVO> getListByPackOrdersList(List<PackOrders> packOrdersList){

        /**
         分析：
         * 1、根据回收员id和打包状态查询打包列表
         * 2、遍历打包列表拿到ids
         * 3、遍历截取ids 拿到 每个订单号id
         * 4、根据订单号id查找得到对应的物品项列表itemList
         * 5、遍历itemList ，List<OrderItemVO> itemVo =  new ArrayList();itemVo设置订单的每一个物品项，add进list里
         * 6、设置CheckOrdersVO
         * 7、CheckOrdersVO添加到list
         */

        //返回的结果对象
       List<CheckOrdersVO> checkOrdersVOList = new ArrayList<>();
        //1、根据回收员id和打包状态查询打包列表
        for (PackOrders packOrders : packOrdersList) {

            CheckOrdersVO checkOrdersVO = new CheckOrdersVO();

//            checkOrdersVO.setPackNo(packOrders.getPackNo());
            String checkCode = null;
            try {
                checkCode = MyEncryptUtils.AESdecrypt(packOrders.getCheckCode());
            } catch (Exception e) {
                e.printStackTrace();
            }
//            checkOrdersVO.setCheckCode(checkCode);

            //  2、遍历打包列表拿到ids
            String ids = packOrders.getOrdersIds();
            //截取id
            String[] splitId = ids.split(",");

            //3、遍历截取ids 拿到 每个订单号id
            //每个订单包含的商品
            List<OrderItemVO> orderItemVOList = new ArrayList<>();
            for (String id : splitId) {
                System.out.println(id);
                //根据id查询订单
                QueryWrapper<Orders> ordersQueryWrapper = new QueryWrapper<>();
                ordersQueryWrapper.eq("id",Long.valueOf(id));
                Orders orders = ordersMapper.selectOne(ordersQueryWrapper);


                //根据订单id查找订单项

                //4、根据订单号id查找得到对应的物品项列表itemList
                List<OrderItem> itemList = orderItemMapper.getOrderItemByOrderId(orders.getId());
                //5、遍历itemList ，List<OrderItemVO> itemVo;itemVo设置订单的每一个物品项，add进list里
                for (OrderItem orderItem : itemList) {
                    //设置每一条商品项数据
                    OrderItemVO orderItemVO = new OrderItemVO();
                    BeanUtils.copyProperties(orderItem, orderItemVO);
                    orderItemVOList.add(orderItemVO);
                }


            }
            //6、设置CheckOrdersVO
            checkOrdersVO.setOrderItemVO(orderItemVOList);
            //7、CheckOrdersVO添加到list
            checkOrdersVOList.add(checkOrdersVO);
        }


        return checkOrdersVOList;


    }
}
